#include <iostream>
#include "Utils/eventloop.h"
#include "Base/address.h"

#include "Http/httpserver.h"
#include "Http/httprequest.h"
#include "Http/httpresponse.h"

#include "Http/httpresponsefile.h"

#define DEBUG

using namespace tiny_muduo;

using tiny_muduo::Method;
using tiny_muduo::HttpStatusCode;

void HttpResponseCallback(const HttpRequest& request, HttpResponse& response)
{
    if(request.method() != kGet)
    {
        response.SetStatusCode(k400BadRequest);
        response.SetStatusMessage("Bad Request");
        response.SetCloseConnection(true);
        return;
    }

    const std::string& path = request.path();
    if(path == "/")
    {
        response.SetStatusCode(k200OK);
        response.SetBodyType("text/html");
        response.SetStatusMessage("OK");
        response.SetBody(love6_website);
    }
    else if(path == "/hello")
    {
        response.SetStatusCode(k200OK);
        response.SetBodyType("text/plain");
        response.SetStatusMessage("OK");
        response.SetBody("Hello, world!\n");
    }
    else if(path == "/favicon.ico")
    {
        response.SetStatusCode(k200OK);
        response.SetBodyType("image/png");
        response.SetStatusMessage("OK");
        response.SetBody(std::string(favicon, sizeof(favicon)));
    }
    else
    {
        response.SetStatusCode(k404NotFound);
        response.SetStatusMessage("Not Found");
        response.SetBody("Sorry, Not Found\n");
        response.SetCloseConnection(true);
    }
}

int main(int argc, char* argv[])
{

#ifndef DEBUG
    if(argc <= 1)
    {
        printf("Usage: %s portname\n", argv[0]);
        return 0;
    }
#endif

    EventLoop loop;

#ifndef DEBUG
    Address listen_address(argv[1]);
#else
    Address listen_address;
#endif

    HttpServer server(&loop, listen_address);
    
    server.SetHttpResponseCallback(HttpResponseCallback);
    server.Start();
    loop.Loop();

    return 0;
}

